<!DOCTYPE html>
<html lang="zn">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  @@include("./head.html")
  <script src="../js/tools/getQueryString.js"></script>
  <title>Document</title>
  <style>
    body {
      padding-top: 70px;
    }

    .section {
      overflow: auto;
    }

    .navbar-header>.navbar-brand>.logo {
      width: 56px;
      margin: -15px 0;
    }

    .media-left>a>.detail-img {
      height: 400px;
    }
  </style>
</head>

<body>
  <header>
    <!-- 头部导航 -->
    <nav class="navbar navbar-default navbar-fixed-top navbar-inverse">
      <div class="container-fluid">
        <!-- 辅助设备 -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
            data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="javascript:;"><img src="../static/img/logo.png" alt="" class="logo"></a>
        </div>

        <!--导航头部 -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <!-- <form class="navbar-form navbar-left">
            <div class="form-group">
              <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
          </form> -->
          <ul class="nav navbar-nav navbar-right">
            <li><a href="javascript:;" class="login-btn">登录 </a></li>
            <li><a href="javascript:;" class="my-cart" role="button">我的购物车 </a>
            </li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
  </header>

  <section class="section">

  </section>
  <!-- 模态框（Modal） -->
  <div class="modal fade" id="identifier" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            &times;
          </button>
          <h4 class="modal-title" id="myModalLabel">
            www.shop.com提示
          </h4>
        </div>
        <div class="modal-body"></div>
        <div class="modal-footer">
          <button type="button" class="btn btn-info btn-close" data-dismiss="modal">关闭
          </button>
        </div>
      </div><!-- /.modal-content -->
    </div><!-- /.modal -->
  </div>
</body>

</html>
<script>
  let goodsList = [];
  const cookie = new Cookie();

  //判断用户登录状态
  function getUserState() {
    if (!cookie.getCookie('userid')) {
      //如果用户未登录，点击按钮登录
      document.querySelector('.login-btn').onclick = () => {
        location.href = './pages/login.html';
      }
    } else {
      //如果用户登录了，登录按钮变为用户的用户名
      document.querySelector('.login-btn').innerText = cookie.getCookie('username');
    }
  }
  getUserState();

  //获取商品详情
  (function () {
    //从地址栏获取商品id
    const obj = getQueryString();
    ajax({
      type: 'post',
      url: '../server/findGood.php',
      data: obj
    }).then(res => {
      goodsList = JSON.parse(res);
      let str = '';
      goodsList.forEach(item => {
        str = str + `
        <div class="container">
          <div class="media">
            <div class="media-left">
              <a href="#">
                <img class="media-object detail-img" src="${item.detail_img}"alt="...">
              </a>
            </div>
          <div class="media-body">
            <h4 class="media-heading">${item.good_name}</h4>
              <p>￥价格：${item.price}</p>
              <button class="btn btn-info btn-sm add-cart" type="button" data-id = ${item.id}>加入购物车</button>
              <button class="btn btn-warning btn-sm add-favor" type="button" data-id = ${item.id}>加入收藏</button>
            </div>
          </div>
        </div>
        `;
      });
      document.querySelector('.section').innerHTML = str;
    })
  })()

  //点击加入收藏与购物车
  document.querySelector('.section').onclick = (e) => {
    //点击加入收藏
    if (e.target.className.includes('add-favor')) {
      //拿到当前点击对象的id
      const id = e.target.getAttribute('data-id');
      //通过id拿到当前点击的对象数组
      const currentList = goodsList.filter(item => item.id == id);
      //将对象数组中的商品信息取出来
      const currentGood = currentList[0];
      var oldArr = localStorage.getItem('favorLists')
      //如果oldArr为空，就将当前点击的商品存入localStorage
      if (!oldArr) {
        localStorage.setItem('favorLists', JSON.stringify([currentGood]));
      } else {
        //如果oldArr不为空，就将当前点击的商品以数组方式存入
        let newArr = JSON.parse(oldArr);
        //遍历本地的数组，将本地中与当前商品id相同的选出来
        const arr = newArr.filter(item => item.id == currentGood.id);
        if (arr.length) {
          //弹出模态框
          $('#identifier').modal('show');
          document.querySelector('.modal-body').innerText = '您已经添加过了,请不要重复添加';
        } else {
          newArr.push(currentGood)
          localStorage.setItem('favorLists', JSON.stringify(newArr));
          //弹出模态框
          $('#identifier').modal('show');
          document.querySelector('.modal-body').innerText = '添加成功';
        }
      }
    } else if (e.target.className.includes('add-cart')) {
      //点击加入收藏
      //判断用户是否登录
      const userid = cookie.getCookie('userid');
      if (!cookie.getCookie('userid')) {
        alert('请登录后操作')
      } else {
        //拿到当前点击对象的id
        const goodId = e.target.getAttribute('data-id');
        ajax({
          type: 'post',
          url: '../server/addCart.php',
          data: {
            userid: userid,
            goodid: goodId
          }
        }).then(res => {
          if (JSON.parse(res).code == 0) {
            // alert('商品已经在购物车中')
            //弹出模态框
            $('#identifier').modal('show');
            document.querySelector('.modal-body').innerText = JSON.parse(res).msg;
          } else {
            // alert('添加成功')
            //弹出模态框
            $('#identifier').modal('show');
            document.querySelector('.modal-body').innerText = JSON.parse(res).msg;
          }
        })
      }
    }
  }


  //进入购物车
  document.querySelector('.my-cart').onclick = () => {
    //如果用户未登录，点击按钮登录
    if (!cookie.getCookie('userid')) {
      location.href = '.login.html';
    } else {
      //如果用户登录了，进入购物车页面
      window.open('./cart.html');
    }
  }

</script>